package cn.amarone.wineblog.models.sys.controller;

import cn.amarone.wineblog.common.constant.CaptchaConst;
import cn.amarone.wineblog.common.appointment.Result;
import cn.amarone.wineblog.config.GlobalConfig;
import cn.hutool.core.lang.UUID;
import com.wf.captcha.ArithmeticCaptcha;
import com.wf.captcha.ChineseCaptcha;
import com.wf.captcha.ChineseGifCaptcha;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** 验证码 */
@RestController
public class CaptchaController {

  @Autowired private GlobalConfig globalConfig;

  public static final int WIDTH = 130;
  public static final int HEIGHT = 48;

  @RequestMapping("/captcha")
  public Result captcha() throws Exception {

    Captcha captcha = build();

    Result result = Result.success();
    result.put(CaptchaConst.VER_KEY, UUID.fastUUID());
    result.put(CaptchaConst.VER_CODE, captcha.toBase64());

    return result;
  }

  private Captcha build() {

    int captchaType = globalConfig.getCaptchaType();

    Captcha captcha = null;

    switch (captchaType) {
      case 0:
        // png类型
        captcha = new SpecCaptcha(WIDTH, HEIGHT);
        break;
      case 1:
        // gif类型
        captcha = new GifCaptcha(WIDTH, HEIGHT);
        break;
      case 2:
        // 中文类型
        captcha = new ChineseCaptcha(WIDTH, HEIGHT);
        break;
      case 3:
        // 中文gif类型
        captcha = new ChineseGifCaptcha(WIDTH, HEIGHT);
        break;
      case 4:
        // 算术类型
        captcha = new ArithmeticCaptcha(WIDTH, HEIGHT);
        //        captcha.getArithmeticString();  // 获取运算的公式：3+2=?
        captcha.text(); // 获取运算的结果：5
        break;
      default:
        break;
    }

    if (captcha instanceof ArithmeticCaptcha) {
      ArithmeticCaptcha ari = (ArithmeticCaptcha) captcha;
      ari.getArithmeticString();
    }

    int captchaCharType = globalConfig.getCaptchaCharType();
    captcha.setCharType(captchaCharType);

    return captcha;
  }
}
